<template>
  <div>
    <h1>分类维护页</h1>
    <el-switch v-model="draggable" active-color="#13ce66" inactive-color="#ff4949"
      :active-value="true"
      :inactive-value="false">
    </el-switch>  开启拖拽

    <el-tree
      :draggable="draggable"
      :allow-drop="allowDrop"
      node-key="catId"
      :default-expanded-keys="defaultExpandedKeys"
      :data="data"
      :props="defaultProps"
      :expand-on-click-node="false"
      @node-drop="nodeDrop"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" @click="() => append(data)">
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => update(data)">
            Update
          </el-button>
          <el-button
            type="text"
            v-if="data.children.length == 0"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <!-- 添加彈窗-->
    <el-dialog title="三級分類" :visible.sync="dialogFormVisible">
      <h2>{{ category }}</h2>
      <el-form :model="category">
        <el-form-item label="分类名称" label-width="120px">
          <el-input v-model="category.name"  label-width="120px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      draggable:false,
      pid: 0,
      countLevel: 0,
      defaultExpandedKeys: [],
      dialogFormVisible: false,
      catLevel: 1,
      level: 1,
      category: {},
      data: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      updateNose: [],
      catLevel: 0,
    };
  },
  methods: {
    //draggingNode 被拖拽的对象
    //dropNode 目标对象
    //type 类型
    nodeDrop(draggingNode, dropNode, type) {
      // console.log(draggingNode,dropNode,type)
      //1.需要重新收集目标对象中的元素
      if (type == "after" || type == "before") {
        this.pid = dropNode.data.parentCid;
        this.catLevel = dropNode.level;
        this.collectNodeList(dropNode.parent.childNodes);
        if (
          draggingNode.level != dropNode.level &&
          draggingNode.childNodes.length != 0
        ) {
          this.catLevel = this.catLevel + 1;
          this.pid = draggingNode.data.catId;
          this.collectNodeList(draggingNode.childNodes);
        }
      } else if (type == "inner") {
        this.pid = dropNode.data.catId;
        this.catLevel = dropNode.level + 1;
        this.collectNodeList(dropNode.childNodes);
      }
      console.log(this.updateNose);
      //给后台发送请求 将收集后的数据进行批量修改
      this.$http({
        url: this.$http.adornUrl(`/product/category/updateNodes`),
        method: "post",
        data: this.$http.adornData(this.updateNose, false),
      }).then(({ data }) => {
        if (data.code == 0) {
          this.$message({
            showClose: true,
            message: "拖拽成功",
            type: "success",
          });
        }
        console.log(data);
      });

      this.updateNose = []; //收集后并进行清空
    },
    collectNodeList(nodes, nodes2) {
      console.log("新的前台对象", nodes, nodes2);

      //收集给后台发送新元素
      for (var i = 0; i < nodes.length; i++) {
        this.updateNose.push({
          catId: nodes[i].data.catId,
          name: nodes[i].data.name,
          parentCid: this.pid,
          sort: i,
          catLevel: this.catLevel,
        }); //push向末尾或数组中添加对象
      }
    },
    /**
     * draggingNode 被拖拽的对象
     * dropNode 目标对象
     * type 拖拽的类型
     */
    allowDrop(draggingNode, dropNode, type) {
      // console.log(draggingNode, dropNode, type);

      //计算被拖拽对象的层数
      this.getCountLevel(draggingNode);
      //  console.log("被拖拽的层数为" + this.countLevel);
      if (type == "next" || type == "prev") {
        //向级别上一个单位或下一个单位中进行拖拽
        if (this.countLevel == 3 && dropNode.level == 1) return true;
        if (this.countLevel == 2 && dropNode.level != 3) return true;
        if (this.countLevel == 1) return true;
      } else if (type == "inner") {
        //向级别之中进行拖拽
        if (this.countLevel == 2 && dropNode.level == 1) return true;
        if (this.countLevel == 1 && dropNode.level != 3) return true;
      }
      return false;
    },
    //计算某一个对象的层数
    getCountLevel(node) {
      // console.log("被拖拽的对象" + node); //如果node为1级分类
      this.countLevel = 1;
      //当前对象如果有子元素  层数+1
      if (node.childNodes.length > 0) {
        //判断是否有二级分类
        this.countLevel = 2;
        for (var i in node.childNodes) {
          if (node.childNodes[i].childNodes.length > 0) {
            //判断二级分类中是否含有3级分类
            //判断是否有二级分类
            this.countLevel = 3;
            break;
          }
        }
      }
    },

    //修改回显
    update(data) {
      this.dialogFormVisible = true;
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.category = data.category; //将修改选中的那条数据直接赋值给对象
      });
    },
    //添加 （修改）
    save() {
      let methodUrl = "save";

      if (this.category.catId) {
        methodUrl = "update";
      }
      this.$http({
        url: this.$http.adornUrl(`/product/category/${methodUrl}`),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        if (data.code == 0) {
          this.$message({
            showClose: true,
            message: "三级分类添加成功",
            type: "success",
          });
          this.dialogFormVisible = false;
          this.getTreeList();
          this.defaultExpandedKeys[0] = this.category.parentCid; //在进行操作后默认展开
          this.category = {}; //清空
        }
        console.log(data);
      });
    },
    //添加
    append(data) {
      //data 为父元素
      this.dialogFormVisible = true;
      this.category.parentCid = data.catId; //对象的id
      this.category.catLevel = data.catLevel + 1;
      console.log(data);
    },

    //删除
    remove(node, data) {
      this.$confirm(`确定对[id=${data.catId}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var ids = [data.catId];
          this.defaultExpandedKeys[0] = data.parentCid; //在进行操作后默认展开
          this.$http({
            url: this.$http.adornUrl(`/product/category/delete`),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getTreeList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    getTreeList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/product/category/treelist"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        console.log(data);
        this.data = data.page;
      });
    },
  },
  created() {
    this.getTreeList();
  },
};
</script>
